const { createApp } = Vue;

createApp({
    data() {
        return {
            users: [],
            searchKey: '',
            currentPage: 1,
            pageSize: 20,
            total: 0,
            batchUsers: '',
            uploading: false,
            uploadProgress: 0,
            currentUploadIndex: 0,
            totalUploadCount: 0,
            batchAddModal: null
        }
    },
    computed: {
        totalPages() {
            return Math.max(1, Math.ceil(this.totalUsers / this.pageSize));
        },
        pageNumbers() {
            const pages = [];
            let start = Math.max(1, this.currentPage - 2);
            let end = Math.min(this.totalPages, start + 4);
            
            if (end - start < 4) {
                start = Math.max(1, end - 4);
            }
            
            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
            return pages;
        },
        uploadProgressText() {
            return `${this.currentUploadIndex} / ${this.totalUploadCount}`;
        }
    },
    methods: {
        async loadUsers() {
            try {
                const response = await fetch(`/api/admin/users?page=${this.currentPage}&size=${this.pageSize}&search=${this.searchKey}`);
                const data = await response.json();
                
                if(data.code === 200) {
                    this.users = data.data;
                    console.log(data.data);
                    this.totalUsers = data.total;
                } else {
                    throw new Error(data.msg || '获取数据失败');
                }
            } catch (error) {
                console.error('加载用户数据失败:', error);
                alert('加载用户数据失败，请刷新重试');
            }
        },
        changePage(page) {
            if (page < 1 || page > this.totalPages) return;
            this.currentPage = page;
            this.loadUsers();
        },
        searchUsers() {
            this.currentPage = 1;
            this.loadUsers();
        },
        handleDelete(user) {
            if (confirm(`确定要删除用户 ${user.username} 吗？`)) {
                // 调用删除API
                alert('删除成功');
                this.loadUsers();
            }
        },
        handleWithdraw(user) {
            const amount = prompt(`请输入提现金额（当前余额：¥${(user.balance/100).toFixed(2)}）：`);
            if (amount && !isNaN(amount)) {
                if (parseFloat(amount) <= user.balance/100) {
                    // 调用提现API
                    alert('提现申请已提交');
                } else {
                    alert('提现金额不能大于余额');
                }
            }
        },
        handleBan(user) {
            const reason = prompt('请输入封禁原因：');
            if (reason) {
                // 调用封禁API
                alert('封禁成功');
                this.loadUsers();
            }
        },
        handleView(user) {
            // 可以打开一个模态框显示用户详情
            alert('查看用户详情：' + user.username);
        },
        closeModal() {
            if (this.batchAddModal) {
                this.batchAddModal.hide();
            }
        },
        handleAdd() {
            this.batchUsers = '';
            if (this.batchAddModal) {
                this.batchAddModal.show();
            } else {
                // 如果模态框实例不存在，重新初始化
                const modalElement = document.getElementById('batchAddModal');
                if (modalElement) {
                    this.batchAddModal = new bootstrap.Modal(modalElement);
                    this.batchAddModal.show();
                }
            }
        },
        async submitBatchUsers() {
            console.log('submitBatchUsers 被调用');
            try {
                const users = this.batchUsers.split('\n')
                    .map(user => user.trim())
                    .filter(user => user);

                console.log('处理后的用户列表:', users);

                if (!users.length) {
                    Swal.fire({
                        icon: 'warning',
                        title: '请输入用户名',
                        text: '用户列表不能为空'
                    });
                    return;
                }

                this.uploading = true;
                this.totalUploadCount = users.length;
                this.currentUploadIndex = 0;
                this.uploadProgress = 0;

                const results = {
                    success: [],
                    failed: []
                };

                for (let i = 0; i < users.length; i++) {
                    const username = users[i];
                    try {
                        console.log('正在添加用户:', username); // 调试日志

                        const response = await fetch('/api/admin/user/create', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                username: username,
                                password: '123456' // 添加默认密码
                            })
                        });

                        const data = await response.json();
                        console.log('添加用户响应:', data); // 调试日志

                        if (data.code === 200) {
                            results.success.push(username);
                        } else {
                            results.failed.push({ username, reason: data.msg || '添加失败' });
                        }
                    } catch (error) {
                        console.error('添加用户出错:', error); // 调试日志
                        results.failed.push({ username, reason: error.message || '网络错误' });
                    }

                    this.currentUploadIndex = i + 1;
                    this.uploadProgress = ((i + 1) / users.length) * 100;
                }

                this.uploading = false;
                this.closeModal();

                // 显示结果
                let message = '';
                if (results.success.length) {
                    message += `成功添加 ${results.success.length} 个用户\n`;
                    message += `成功列表：${results.success.join(', ')}\n\n`;
                }
                if (results.failed.length) {
                    message += `添加失败 ${results.failed.length} 个用户：\n`;
                    results.failed.forEach(({ username, reason }) => {
                        message += `${username}: ${reason}\n`;
                    });
                }

                await Swal.fire({
                    icon: results.failed.length ? 'warning' : 'success',
                    title: '添加完成',
                    html: message.replace(/\n/g, '<br>'),
                    confirmButtonText: '确定'
                });

                // 刷新用户列表
                this.loadUsers();
            } catch (error) {
                console.error('批量添加用户失败:', error);
                this.uploading = false;
                Swal.fire({
                    icon: 'error',
                    title: '操作失败',
                    text: error.message || '批量添加用户时发生错误'
                });
            }
        }
    },
    mounted() {
        console.log('Vue 实例已挂载');
        this.loadUsers();
        this.$nextTick(() => {
            // 初始化模态框
            const modalElement = document.getElementById('batchAddModal');
            if (modalElement) {
                this.batchAddModal = new bootstrap.Modal(modalElement, {
                    backdrop: 'static',
                    keyboard: false
                });
            } else {
                console.error('找不到模态框元素');
            }
        });
    }
}).mount('#userApp'); 